package com.hangxintong.common.utils.aop;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.hangxintong.common.base.entity.LmUser;
import com.hangxintong.common.base.service.LockService;
import com.hangxintong.common.config.HeaderHolder;
import com.hangxintong.common.exception.SystemErrorCodeMark;
import com.hangxintong.common.exception.SystemException;
import com.hangxintong.common.utils.Result;
import com.hangxintong.common.utils.annon.NoRepeatSubmit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @Auther: tsj
 * @Date: 2021/2/26 09:23
 * @Description:防重复切面类
 */
@Aspect
@Component
public class NoRepeatSubmitAspect {

    private static final Logger logger = LoggerFactory.getLogger(NoRepeatSubmitAspect.class);

    private static Gson gson = new Gson();

    private static  final  String SUFFIX = "SUFFIX";

    //锁前缀
    private static final String NO_REPEAT_LOCK_PREFIX ="iflow:no_repeat_lock:";

    @Autowired
    LockService lockService;

    @Autowired
    HeaderHolder headerHolder;

    /**
     * 设置注解切点
     * @param noRepeatSubmit
     */
    @Pointcut("@annotation(noRepeatSubmit)")
    public void repeatPoint(NoRepeatSubmit noRepeatSubmit){

    }
    /**
     * 设置注解环绕增强
     */
    @Around(value = "repeatPoint(noRepeatSubmit)")
    public Object doBefore(ProceedingJoinPoint joinPoint,NoRepeatSubmit noRepeatSubmit){

        try {
            String key = NO_REPEAT_LOCK_PREFIX + noRepeatSubmit.locationo();
            Object[] args = joinPoint.getArgs();
            String name = noRepeatSubmit.name();
            int argIndex = noRepeatSubmit.argIndex();
            String suffix;
            int type = noRepeatSubmit.type();

            if (type==0){
                 LmUser user = headerHolder.getHeader().getUser();
                 key+=":"+user.getId();
            }

            if (StringUtils.isEmpty(name)) {
//                suffix = String.valueOf(args[argIndex]);
                suffix = SUFFIX;
            } else {

                Map<String, Object> keyAndValue = getKeyAndValue(args[argIndex]);
                Object valueObject = keyAndValue.get(name);
                if (valueObject == null) {
                    suffix = SUFFIX;
                } else {
                    suffix = String.valueOf(valueObject);
                }
            }
            key = key + ":" + suffix;
            logger.info("==================================================");
            for (Object arg : args) {
                logger.info(gson.toJson(arg));
            }

            logger.info("==================================================");
            int seconds = noRepeatSubmit.seconds();
            logger.info("lock key : " + key);
            if (!lockService.isLock(key, seconds)) {
                return new Result(false, 500, "操作过于频繁，请稍后重试");
            }
            try {
                Object proceed = joinPoint.proceed();
                return proceed;
            } catch (Throwable throwable) {
                logger.error("运行业务代码出错", throwable);
                throw new RuntimeException(throwable.getMessage());
            } finally {
//                lockService.unLock(key);
            }

        }catch (Exception e){
            throw new SystemException(SystemErrorCodeMark.Code.SYSTEM_ERROR_LOCAL,e.getMessage());
        }
    }



    public static Map<String, Object> getKeyAndValue(Object obj) {
        Map<String, Object> map = Maps.newHashMap();
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            // 设置些属性是可以访问的
            f.setAccessible(true);
            Object val = new Object();
            try {
                val = f.get(obj);
                // 得到此属性的值
                // 设置键值
                map.put(f.getName(), val);
            } catch (IllegalArgumentException e) {
                logger.error("getKeyAndValue IllegalArgumentException", e);
            } catch (IllegalAccessException e) {
                logger.error("getKeyAndValue IllegalAccessException", e);
            }

        }
        logger.info("扫描结果：" + gson.toJson(map));
        return map;
    }


}
